package com.theaf.basemodule.service.other;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.theaf.core.utils.SmExceptionHelper;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:songwenke
 * @Description:站内消息的服务
 * @Date:create in 11:48 2018/3/27
 * @Modified By:
 **/
@Component
public class SiteMesService {
    private Map<Long,List<SocketIOClient>> clientMap = new HashMap();

    @OnConnect
    public void onConnect(SocketIOClient client) {
        Long uid = Long.parseLong(client.getHandshakeData().getSingleUrlParam("uid"));
        List<SocketIOClient> list = clientMap.get(uid);
        if(list==null){
            list = new ArrayList();
        }
        list.add(client);
        clientMap.put(uid,list);
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        Long uid = Long.parseLong(client.getHandshakeData().getSingleUrlParam("uid"));
        List<SocketIOClient> list = clientMap.get(uid);
        if(list!=null){
            list.forEach(n->{
                if(n.equals(client)){
                    list.remove(n);
                }
            });
        }
        clientMap.put(uid,list);
    }

    @OnEvent(value = "sendMsg")
    public void sendMsg(SocketIOClient client, AckRequest request, Object sendData){

    }

    /**
     * 发送消息
     * @param userId 用户id
     * @param userName 用户名
     * @param content 发送内容
     */
    public void sendMsg(Long userId,String userName,String content){
        List<SocketIOClient> list = clientMap.get(userId);
        if(list==null||list.isEmpty()){
            throw SmExceptionHelper.sysCheckException(userName+"此用户不在线");
        }
        list.forEach(c->{
            c.sendEvent("sendMsg", content);
        });
    }
}
